package com.demo.controller;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

@Controller
@RequestMapping("/u")
public class UploadifyController {

	//上传文件的保存路径
	protected String configPath = "attached/";
	protected String dirTemp = "attached/temp/";

	@RequestMapping("/index")
	public String index() {
		return "spring-uploadify";
	}

	SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");

	@RequestMapping("/uploadify1")
	public void uploadify1(HttpServletRequest request, HttpServletResponse response) throws Exception {
		String realPath = request.getSession().getServletContext().getRealPath("/");
		//文件保存目录路径
		String savePath = realPath + configPath;
		// 临时文件目录 
		String tempPath = realPath + dirTemp;
		//		FileUtils.copyInputStreamToFile(myfile.getInputStream(), new File(savePath, myfile.getOriginalFilename()));
		//
		//		File dirTempFile = FileInfo.newFile(tempPath);
		//		DiskFileItemFactory factory = new DiskFileItemFactory();
		//		factory.setSizeThreshold(20 * 1024 * 1024); //设定使用内存超过5M时，将产生临时文件并存储于临时目录中。   
		//		factory.setRepository(dirTempFile); //设定存储临时文件的目录。   
		//
		//		ServletFileUpload upload = new ServletFileUpload(factory);
		//		upload.setHeaderEncoding("UTF-8");
		//
		//		try {
		//			List<FileItem> items = upload.parseRequest(request);
		//			Iterator<FileItem> itr = items.iterator();
		//
		//			while (itr.hasNext()) {
		//				FileItem item = itr.next();
		//				if (!item.isFormField()) {
		//					try {
		//						FileInfo fieleInfo = new FileInfo(item);
		//						fieleInfo.write(savePath, fieleInfo.getName() + df.format(new Date()));
		//						System.out.println("上传成功！路径：" + savePath + "/" + fieleInfo.getName() + df.format(new Date()));
		//					} catch (Exception e) {
		//						e.printStackTrace();
		//					}
		//				}
		//			}
		//			out.flush();
		//		} catch (FileUploadException e) {
		//			e.printStackTrace();
		//		} finally {
		//			IOUtils.closeQuietly(out);
		//		}
	}

	@RequestMapping(value = "/uploadify", method = RequestMethod.POST)
	public void uploadify(@RequestParam("uploadify") MultipartFile[] uploadifys, HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		/**页面控件的文件流**/
		for (MultipartFile multipartFile : uploadifys) {

			/**获取文件的后缀**/
			String logImageName = multipartFile.getOriginalFilename();
			/**拼成完整的文件保存路径加文件**/
			String fileName = File.separator + logImageName;
			System.out.println(fileName);
		}
		System.out.println(111111);
	}

	public static class FileInfo {
		private String fullName;// 文件全名
		private String name;// 文件名
		private String ext;// 扩展名
		private FileItem fileItem;

		public FileInfo(FileItem fileItem) {
			this.fileItem = fileItem;
			this.fullName = fileItem.getFieldName();
			this.afterPropertiesSet();
		}

		protected void afterPropertiesSet() {
			int lastPointIndex = fullName.lastIndexOf(".");
			this.ext = fullName.substring(lastPointIndex + 1).toLowerCase();
			this.name = fullName.substring(0, lastPointIndex);
		}

		public void write(File file) throws IOException {
			OutputStream os = null;
			InputStream is = null;
			try {
				is = fileItem.getInputStream();
				os = new FileOutputStream(file);

				byte buf[] = new byte[1024];//可以修改 1024 以提高读取速度
				for (int length = 0; (length = is.read(buf)) > 0;) {
					os.write(buf, 0, length);
				}
				// 刷新
				os.flush();
			} finally {
				IOUtils.closeQuietly(os);
				IOUtils.closeQuietly(is);
			}
		}

		public void write(String savePath, String name) throws IOException {
			write(new File(savePath, name + "." + ext));
		}

		public String getFullName() {
			return fullName;
		}

		public String getName() {
			return name;
		}

		public String getExt() {
			return ext;
		}

		public FileItem getFileItem() {
			return fileItem;
		}

		public static File newFile(String pathname) {
			File file = new File(pathname);
			if (!file.exists()) {
				// 创建目录
				if (file.isDirectory()) file.mkdirs();
			}
			return file;
		}
	}
}
